﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Passwords.Properties;
using Passwords.DAL;
using Passwords.Services;
using System.IO;
using System.Runtime.Serialization;
using System.Diagnostics;

namespace Passwords.Utils
{
    public static class DbInitializerUtil
    {
        public static void InitializeDb()
        {
            if (Settings.Default.IsDbEmpty)
            {
                try
                {
                    using (DataContext context = new DataContext())
                    {
                        Backup backup = GetDefaultDb();
                        if (backup == null) throw new ArgumentNullException("backup");

                        //                    context.DeleteDatabase();
                        context.Login(new System.Security.SecureString());
                        context.RestoreBackup(backup);
                    }

                    Settings.Default.IsDbEmpty = false;
                    Settings.Default.Save();
                }
                catch (Exception ex)
                {
                    if (Debugger.IsAttached) Debugger.Break();
                    Debug.WriteLine(ex.Message);
                }
            }
        }

        private static Backup GetDefaultDb()
        {
            using (MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(AppResources.EmptyDb)))
            {
                stream.Position = 0;
                DataContractSerializer serializer = new DataContractSerializer(typeof(Backup));
                Backup backup = serializer.ReadObject(stream) as Backup;
                return backup;

            }
        }
    }
}
